<template>
  <el-dialog
    title="分配线索"
    :visible.sync="dialogVisible"
    width="600px"
  >
    <el-form>
      <el-form-item label="选择员工:">
        <el-select
          v-model="selectedEmployee"
          placeholder="请选择员工"
          :loading="employeeListLoading"
        >
          <el-option
            v-for="employee in employeeList"
            :key="employee.id"
            :label="employee.name"
            :value="employee.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="submitting"
        @click="handleConfirm"
      >
        确定
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { apiSelectUser } from '@/api/system'
import { apiCustomerAssignMany } from '@/api/clue'

export default {
  name: 'AssignDialog',
  props: {
    // 接收客户 ids
    khIds: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      selectedEmployee: '',
      employeeList: [],
      employeeListLoading: false,
      submitting: false
    }
  },
  methods: {
    // 打开弹窗并获取员工列表
    async openDialog() {
      this.dialogVisible = true
      this.selectedEmployee = ''
      await this.fetchEmployeeList()
    },
    // 获取员工列表
    async fetchEmployeeList() {
      this.employeeListLoading = true
      try {
        const response = await apiSelectUser()
        this.employeeList = response.data.map((item) => ({
          id: item.number_id, // 假设员工 id 字段为 id
          name: item.name // 假设员工姓名为 name
        }))
      } finally {
        this.employeeListLoading = false
      }
    },
    // 处理确认分配操作
    async handleConfirm() {
      if (!this.selectedEmployee) {
        this.$message.warning('请选择员工')
        return
      }
      this.submitting = true
      try {
        await apiCustomerAssignMany({
          kh_ids: this.khIds,
          user_number_id: this.selectedEmployee
        })
        this.$message.success('分配成功')
        this.dialogVisible = false
        this.$emit('assign-success')
      } catch (error) {
        this.$message.error('分配失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped></style>
